package com.kabuda.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kabuda.blog.dao.pojo.SysUser;
import com.kabuda.blog.service.LoginService;
import com.kabuda.blog.service.SysUserService;
import com.kabuda.blog.vo.LoginUserVo;
import com.kabuda.blog.vo.Result;
import com.kabuda.blog.vo.UserVo;
import com.kabuda.blog.dao.mapper.SysUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author kabuda
 * @create 2023-01-16 15:32
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;


    @Autowired
    LoginService loginService;


    @Override
    public SysUser getUserById(Long authorId) {
        SysUser sysUser = sysUserMapper.selectById(authorId);
        return sysUser;
    }

    @Override
    public SysUser findUser(String account, String password) {
        LambdaQueryWrapper<SysUser> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getAccount,account).eq(SysUser::getPassword,password);
        queryWrapper.select(SysUser::getId,SysUser::getAccount,SysUser::getNickname,SysUser::getAvatar);
        queryWrapper.last("limit 1");
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        return sysUser;
    }


    @Override
    public Result currentUser(String authorization) {
        SysUser sysUser=loginService.checkToken(authorization);
        LoginUserVo loginUserVo = new LoginUserVo();
        BeanUtils.copyProperties(sysUser,loginUserVo);
        return Result.success(loginUserVo);
    }

    @Override
    public boolean findUserByAccount(String account) {
        LambdaQueryWrapper<SysUser> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getAccount,account).last("limit 1");
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        if(sysUser==null){
            return true;
        }
        return false;
    }

    @Override
    public void saveUser(SysUser sysUser) {
        sysUserMapper.insert(sysUser);
    }

    @Override
    public UserVo findUserVoById(Long id) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getId,id);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(sysUser,userVo);
        return userVo;

    }
}
